package middlewares

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"study_abroad_system_back_end/common"
	"study_abroad_system_back_end/common/StatusCode"
	"study_abroad_system_back_end/response"
	"time"
)

func TokenMiddleWare() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		code := 200
		token := ctx.GetHeader("Authorization")
		if token == "" {
			code = StatusCode.ERROR_TOKEN_NOT_EXIST
		} else {
			token = token[7:]
			claims, err := common.ParseToken(token)
			if err != nil {
				code = StatusCode.ERROR_AUTH_CHECK_TOKEN_FAIL
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = StatusCode.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
			}
		}
		if code != StatusCode.SUCCESS {
			response.Response(ctx, http.StatusInternalServerError, code, nil, StatusCode.GetMsg(code))
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}
